import sys
import os
import json
sys.path.append(os.getcwd())
from lib.apis import aep_device_management,aep_device_status
from serial_op import cereg_sta_check
from serial_op import mqServerSend, at_ser_identify
'''
在AEP平台创建设备
输入：deviceName,deviceSn,operator,productId,appKey,appSecret,MasterKey (str)
返回：device_id,token (str) （设备在平台已创建，token为空）
result返回格式：
result = b'{"code":0,
"msg":"ok",
"result":{"deviceSn":"898612334",
    "deviceId":"17167017898612334",
    "deviceName":"CTL03",
    "tenantId":"2000361877",
    "productId":17167017,
    "imei":null,
    "token":"34-h4KI-UWcpqjzgf9v2SpPXbBK0EJYAdP9iS2gJpJw"}}'
'''
def aep_dev_create(deviceName,deviceSn,operator,productId,appKey,appSecret,MasterKey):
    body = {"deviceName": deviceName,"deviceSn": deviceSn,"imei": '',"operator": operator,"other": {},"productId": productId}
    json_body = json.dumps(body)
    result = aep_device_management.CreateDevice(appKey, appSecret, MasterKey, json_body )
    #print(result)
    result_dict = json.loads(result.decode('utf-8'))  #将字符串解析为 JSON 对象
    code = result_dict['code']
    token = ''
    device_id = ''
    if code == 0: #设备创建成功
        device_id = result_dict['result']['deviceId']
        token = result_dict['result']['token']
    return code, device_id, token

'''
获取设备在线状态：在线-True，不在线-False
result返回格式：
result=b'{"code":0,"msg":"ok",
"result":{"deviceId":"1716701712345678","deviceName":"CTL03",
"tenantId":"2000361877","productId":17167017,
"deviceSn":"12345678","firmwareVersion":"",
"deviceStatus":0,"createTime":1735002090604,
"updateTime":null,"activeTime":null,"logoutTime":null,
"netStatus":null,"onlineAt":null,"offlineAt":null,
"productProtocol":2}}'
'''
def aep_dev_status(appKey, appSecret, MasterKey, deviceId, productId):
    result = aep_device_management.QueryDevice(appKey, appSecret, MasterKey, deviceId, productId)
    result_dict = json.loads(result.decode('utf-8'))  #将字符串解析为 JSON 对象
    code = result_dict['code']
    dev_status = False
    if code == 0 and result_dict['result']['netStatus'] == 1: #查询成功且设备状态为在线
        dev_status = True
    return dev_status

def server_switch_test(at_port, baudrate, timeout, servercfg, appKey, appSecret, MasterKey, deviceId, productId):

    # 下发服务器参数
    response = mqServerSend(servercfg, at_port, baudrate, timeout)
    if response is None:
        return -1  #串口通信失败
    # 检查模组是否驻网
    if cereg_sta_check(at_port, baudrate, timeout):
        # 检查设备是否上线
        if aep_dev_status(appKey, appSecret, MasterKey, deviceId, productId):
            return 0 #设备已上线
        else:
            return 1 #设备未上线
    else:
        return 2 #模组未驻网
    
if __name__ == '__main__':
    #res = aep_device_management.QueryDeviceList('bkEnIQhmDkl', 'y8A76tLm6f', 'b9e0de4726d3447db573bcf077e250f4', '17167017')
    deviceName = 'CTL03'
    deviceSn = '12345678'
    operator = 'liuyuye'
    productId = '17167017'
    appKey = 'bkEnIQhmDkl'
    appSecret = 'y8A76tLm6f'
    MasterKey = 'b9e0de4726d3447db573bcf077e250f4'
    hostname = 'mqtt.ctwing.cn'
    port = 1883
    baudrate = 115200
    timeout = 1
    server_params = {
    "servertype":"control",
    "hostname": "mqtt.ctwing.cn",
    "port": 1883,
    "clientid":"1716701712345678",
    "username": "liuyuye",
    "password": "WdGi3iu7xoEanpYVX7uocBcTvb8-lSkkQO0QOBf1lJA"
    }
    at_ports = at_ser_identify()
    print("AT口：{}".format(at_ports))
    at_commands = ['ATI','AT+CGSN=1','AT+CEREG?','AT+QCCID?']
    for at_port in at_ports:
        result = server_switch_test(at_port, baudrate, timeout, server_params, appKey, appSecret, MasterKey, productId + deviceSn, productId)
        print(result)
    '''
    code,deviceid,token = aep_dev_create(deviceName, deviceSn, operator, productId, appKey, appSecret,MasterKey)
    print('code-{},deviceid={},token={}'.format(code,deviceid,token))

    res = aep_dev_status(appKey,appSecret, MasterKey, productId+deviceSn, productId)
    print(res)
    '''
    
    


